<template>
  <div class="book">
    <div class="main-title">书籍管理</div>
    <el-card class="box-card" v-loading="isLoading">
      <!-- 头部表单 -->
      <div slot="header" class="clearfix">
        <el-form
          ref="form"
          :model="query"
          label-position="left"
          label-width="60px"
          inline
        >
          <el-form-item
            label="类别"
            prop="type"
          >
            <el-select
              v-model="query.type"
              placeholder="书籍类别"
              clearable
            >
              <el-option
                v-for="item in typeList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item
            label="书名"
            prop="bookName"
          >
            <el-input
              v-model="query.bookName"
            ></el-input>
          </el-form-item>
          <el-form-item
            label="书号"
            prop="bookId"
          >
            <el-input v-model="query.bookId"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button
              type="primary"
              @click.native="handleQuery"
            >查询</el-button>
          </el-form-item>
          <el-form-item>
            <el-button @click.native="handleReset">重置</el-button>
          </el-form-item>
          <el-form-item>
            <el-button
              type="primary"
              @click.native="handleCreate"
            >添加书本</el-button>
          </el-form-item>
        </el-form>
      </div>
      <!-- 底部表格 -->
      <el-table
        :data="books"
        stripe
      >
        <el-table-column
          align="center"
          prop="bookId"
          label="书号"
        ></el-table-column>
        <el-table-column
          align="center"
          prop="type"
          label="类别"
        >
          <template slot-scope="scope">
            {{ scope.row.type | typeFilter }}
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          prop="bookName"
          label="书名"
        ></el-table-column>
        <el-table-column
          align="center"
          prop="coverUrl"
          label="封面"
        >
          <template slot-scope="scope">
            <el-image
              :src="scope.row.coverUrl"
              style="width: 60px; height: 75px;"
              fit="cover"
              :preview-src-list="[scope.row.coverUrl]"
            ></el-image>
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          prop="remain"
          label="库存"
        ></el-table-column>
        <el-table-column
          align="center"
          prop="amount"
          label="总数"
        >
        </el-table-column>
        <el-table-column
          align="center"
          prop="status"
          label="可借状态"
        >
          <template slot-scope="scope">
            <el-tag
              v-if="scope.row.status"
              type="success"
            >可借阅</el-tag>
            <el-tag
              v-else
              type="danger"
            >不外借</el-tag>
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          width="300"
          label="操作"
        >
          <template slot-scope="scope">
            <el-button @click.native="handleEdit(scope.row)">编辑</el-button>
            <el-button @click.native="handleRemove(scope.row)" type="danger">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        layout="prev, pager, next"
        :total="pager.total"
        :page-size="pager.pageSize"
        :current-page="pager.curPage"
        @current-change="handlePageChange"
      >
      </el-pagination>
    </el-card>
  </div>
</template>

<script>
import { getAllBooks, getTypeList, queryBooks } from '@/services/book'
export default {
  name: 'Book',
  data () {
    return {
      // 查询表格
      query: {
        bookName: '',
        bookId: '',
        type: ''
      },
      // 展示书籍
      books: [],
      // 表格类别内容
      typeList: [],
      pager: {
        pageSize: 5,
        curPage: 1,
        total: 0
      },
      // 控制是否加载中
      isLoading: false,
      // 判断是否分页中查询
      isPaging: false
    }
  },
  created () {
    this.loadBooks()
    this.loadTypeList()
  },
  methods: {
    // 加载分页所有书本
    async loadBooks () {
      this.isLoading = true
      const { data } = await getAllBooks(this.pager)
      if (data.errcode === 0) {
        const books = []
        data.data.forEach(item => {
          books.push(JSON.parse(item))
        })
        this.books = books
        this.pager.total = data.booksLength
      } else {
        this.$message.error('书籍信息拉取失败，请联系开发者')
      }
      this.isLoading = false
    },
    // 加载查询的下拉列表内容
    async loadTypeList () {
      const { data } = await getTypeList()
      if (data.errcode === 0) {
        data.data.forEach(item => {
          const type = JSON.parse(item)
          this.typeList.push({
            label: type.label,
            value: type.typeId
          })
        })
      }
    },
    // 查询
    async handleQuery () {
      // 如果查询条件全空，当做刷新一次
      if (!this.isPaging) {
        this.pager.curPage = 1
      } else {
        this.isPaging = false
      }
      if (!this.query.bookName && !this.query.bookId && !this.query.type) {
        await this.loadBooks()
      } else {
        this.isLoading = true
        const body = {
          curPage: this.pager.curPage,
          pageSize: this.pager.pageSize,
          bookName: this.query.bookName,
          bookId: this.query.bookId,
          type: this.query.type
        }
        const { data } = await queryBooks(body)
        if (data.errcode === 0) {
          const books = []
          data.data.forEach(item => {
            books.push(JSON.parse(item))
          })
          this.books = books
          if (this.books.length > 0) {
            body.pageSize = -1
            const { data } = await queryBooks(body)
            if (data.errcode === 0) {
              this.pager.total = data.data.length
            } else {
              this.$message.error('获取总条数失败')
            }
          } else {
            this.pager.total = 0
          }
          this.$message.success('查找完成！')
        } else {
          this.$message.error('查找失败！请联系开发者')
        }
      }
      this.isLoading = false
    },
    // 编辑
    handleEdit (rowData) {
      this.$router.push({
        name: 'edit-book',
        params: {
          bookId: rowData.bookId
        }
      })
    },
    // 删除
    handleRemove () {
      this.$confirm('确定删除吗？删除后不可恢复！', '警告', {
        confirmButtonText: '删除',
        cancelButtonText: '取消',
        type: 'error'
      }).then(res => {
        this.$message.success('删除成功')
      }).catch(() => {
        this.$message.info('取消删除')
      })
    },
    // 添加
    handleCreate () {
      this.$router.push({
        name: 'create-book'
      })
    },
    // 控制分页
    handlePageChange (curPage) {
      this.pager.curPage = curPage
      if (!this.query.bookName && !this.query.bookId && !this.query.type) {
        this.loadBooks()
      } else {
        this.isPaging = true
        this.handleQuery()
      }
    },
    // 重置表单
    handleReset () {
      this.$refs.form.resetFields()
    }
  },
  filters: {
    // 将数字的书类别转换成字母
    typeFilter (value) {
      return String.fromCharCode(parseInt(value) + 64)
    }
  }
}
</script>

<style lang="scss" scoped>
@import url('~@/styles/my-button.scss');
@import url('~@/styles/my-form.scss');
</style>
